package com.approval.security;

import com.approval.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 权限验证工具类
 */
@Component
public class PermissionUtils {
    
    @Autowired
    private AuthService authService;
    
    /**
     * 检查当前用户是否有指定权限
     */
    public boolean hasPermission(String permissionCode) {
        Long userId = getCurrentUserId();
        if (userId == null) {
            return false;
        }
        return authService.hasPermission(userId, permissionCode);
    }
    
    /**
     * 检查当前用户是否有指定资源和操作的权限
     */
    public boolean hasPermission(String resource, String action) {
        Long userId = getCurrentUserId();
        if (userId == null) {
            return false;
        }
        return authService.hasPermission(userId, resource, action);
    }
    
    /**
     * 检查指定用户是否有指定权限
     */
    public boolean hasPermission(Long userId, String permissionCode) {
        return authService.hasPermission(userId, permissionCode);
    }
    
    /**
     * 检查指定用户是否有指定资源和操作的权限
     */
    public boolean hasPermission(Long userId, String resource, String action) {
        return authService.hasPermission(userId, resource, action);
    }
    
    /**
     * 获取当前用户ID
     */
    public Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        // 这里需要根据你的认证方式实现
        // 假设用户信息存储在authentication的principal中
        if (authentication.getPrincipal() instanceof org.springframework.security.core.userdetails.UserDetails) {
            // 从UserDetails中获取用户ID
            // 这里需要根据你的实际实现调整
            return 1L; // 临时返回1，实际应该从认证信息中获取
        }
        
        return null;
    }
    
    /**
     * 获取当前用户名
     */
    public String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        return authentication.getName();
    }
    
    /**
     * 检查当前用户是否为超级管理员
     */
    public boolean isSuperAdmin() {
        return hasPermission("SUPER_ADMIN");
    }
    
    /**
     * 检查当前用户是否为系统管理员
     */
    public boolean isAdmin() {
        return hasPermission("ADMIN");
    }
}
